package com.ruoyi.tongban.utils;

import com.ruoyi.common.utils.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class PushCameraUtils {
  
  private static String key = "4ef70966abf7e76d634527e66060fd24";//key值
  
  private static String push_domain = "rtmp://push.dqbenxin.com/";//推流域名
  
//  private static String play_domain = "http://live.dqbenxin.com/";//播放域名
private static String play_domain = "://live.dqbenxin.com/";//播放域名




  private static final char[] DIGITS_LOWER =
          {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  /*
   * 获取推流相关参数
   */
  public static Map<String, String> getPushUrl(String appName, String txTime) {
    
    Long exTime = getUnixTime(txTime);
    
    String streamName = RandomUtils.getString();//随机6位字符串
    String input = new StringBuilder().
            append(key).
            append(streamName).
            append(Long.toHexString(exTime).toUpperCase()).toString();
    String txSecret = null;
    try {
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      txSecret  = byteArrayToHexString(
              messageDigest.digest(input.getBytes("UTF-8")));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    
    //推流地址,格式:rtmp://domain/AppName/StreamName?txSecret=Md5(key+StreamName+hex(time))&txTime=hex(time)
    String pushStream = push_domain + appName + "/" + streamName + "?txSecret=" + txSecret + "&txTime=" + Long.toHexString(exTime).toUpperCase();
    //rtmp地址
    String cameraRtmp = "http"+play_domain + appName + "/" + streamName + ".m3u8";
    //http地址
    String cameraHttp = "rtmp"+play_domain + appName + "/" + streamName;
    
    Map<String, String> returnMap = new HashMap<String, String>();
    returnMap.put("pushStream", pushStream);
    returnMap.put("cameraRtmp", cameraRtmp);
    returnMap.put("cameraHttp", cameraHttp);
    return returnMap;
  }
  
  /**
   * 获取unix时间戳
   * @return
   * @throws Exception
   */
  private static Long getUnixTime(String dateStr) {
    
    try {
      
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      
      long epoch = df.parse(dateStr).getTime();
      
      return epoch/1000;
      
    } catch (ParseException e) {
      e.printStackTrace();
    }
    
    return 0L;
  }
  
  private static String byteArrayToHexString(byte[] data) {
    char[] out = new char[data.length << 1];
    for (int i = 0, j = 0; i < data.length; i++) {
      out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
      out[j++] = DIGITS_LOWER[0x0F & data[i]];
    }
    return new String(out);
  }
}
